package com.ruoyi.web.controller.mes;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.pinyin.PinYinUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.web.mapper.MesConfigMapper;
import com.ruoyi.web.mapper.MesCoveringMapper;
import com.ruoyi.web.mapper.ProduceMapper;
import com.ruoyi.web.service.*;
import com.ruoyi.web.vo.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/covering")
public class MesCoveringController extends BaseController {
    @Resource
    private MesCoveringService mesCoveringService;
    @Resource
    private MesCoveringUserService mesCoveringUserService;
    @Resource
    private MesCoveringWorkService mesCoveringWorkService;
    @Resource
    private MesConfigMapper configMapper;
    @Resource
    private MesMachineService mesMachineService;
    @Resource
    private ProducePieceService producePieceService;
    @Resource
    private MesProducePieceMachineService producePieceMachineService;
    @Resource
    private ProduceMapper produceMapper;

    @Resource
    private ProduceService produceService;

    @Resource
    private MesQualityService mesQualityService;

    @Resource
    private MesQualityUserService mesQualityUserService;

    @Resource
    private MesQualityWorkService mesQualityWorkService;

    @Resource
    private IMesReportWork MesReportWork;
    @Resource
    private MesCoveringMapper mesCoveringMapper;

    @PostMapping(value = "/list")
    public TableDataInfo list(@RequestBody Map<String, String> params) {
//        startPage(params);
//        String orderDate = params.get("orderDate");
//        String coverNo = params.get("coverNo");
//        String status = params.get("status");
//        return getDataTable(mesCoveringService.list(new QueryWrapper<MesCovering>().lambda()
//                .like(StringUtils.isNotEmpty(coverNo), MesCovering::getCoverNo, coverNo)
//                .like(StringUtils.isNotEmpty(orderDate), MesCovering::getOrderDate, orderDate)
//                .eq(StringUtils.isNotEmpty(status), MesCovering::getStatus, status)
//                .orderByDesc(MesCovering::getCreateTime)
//        ));
        startPage(params);
        MesCovering mesCovering = new MesCovering();
        mesCovering.setParams(params);
        List<MesCovering> list = mesCoveringMapper.selectMesCoveringList(mesCovering);
        return getDataTable(list);
    }

    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody MesCovering mesCovering) {
        // 新增
        if (mesCovering.getPid() == null) {
            mesCovering.setPid(UUID.randomUUID().toString().replace("-", ""));

            mesCovering.setCreateTime(DateUtils.getNowDate());
            mesCovering.setCreateBy(SecurityUtils.getUsername());

            if (mesCovering.getOrderUserList() != null) {
                mesCovering.getOrderUserList().forEach(e -> {
                    e.setOrderId(mesCovering.getPid());
                });
            }
            if (mesCovering.getOrderWorkList() != null) {
                mesCovering.getOrderWorkList().forEach(e -> {
                    e.setOrderId(mesCovering.getPid());
                });
            }
        }
        // 修改
        else {
            mesCovering.setUpdateTime(DateUtils.getNowDate());
            mesCovering.setUpdateBy(SecurityUtils.getUsername());
        }

        if (mesCovering.getOrderUserList() != null && mesCovering.getOrderUserList().size() != 0) {
            for (MesCoveringUser coveringUser : mesCovering.getOrderUserList()) {
                coveringUser.setOrderId(mesCovering.getPid());
            }
        }
        if (mesCovering.getOrderWorkList() != null && mesCovering.getOrderWorkList().size() != 0) {
            for (MesCoveringWork coveringWork : mesCovering.getOrderWorkList()) {
                coveringWork.setOrderId(mesCovering.getPid());
            }
        }

//        // 判断当前步骤的报工量不能大于上一步骤的报工量
//        String failureMsg = MesReportWork.checkMesReportPreviousStep(mesCovering, "7");  // 覆膜报工
//        if (StringUtils.isNotEmpty(failureMsg)) {
//            return AjaxResult.warn(failureMsg);
//        }

        // 上报主表机台id
        String machineId = mesCovering.getMachineId();
        MesMachine mesMachine = mesMachineService.getById(machineId);
        String machineType = mesMachine.getType();

        if (mesCovering.getOrderWorkList() != null && mesCovering.getOrderWorkList().size() != 0) {
            for (MesCoveringWork mesCoveringWork : mesCovering.getOrderWorkList()) {
                String state = "2";
                if (machineType.equals("7")) {//覆膜
                    producePieceService
                            .update(new UpdateWrapper<ProducePiece>().lambda()
                                    .set(ProducePiece::getCoveringState, state)
                                    .eq(ProducePiece::getPieceId, mesCoveringWork.getPieceId())
                            );
                }

                // 查询贴的信息
                ProducePiece producePiece = producePieceService.getById(mesCoveringWork.getPieceId());
                // boolean finish = true; // 贴的每一步骤是否全部完成
                int num = 0;
                List<MesProducePieceMachine> list = producePieceMachineService.list(new QueryWrapper<MesProducePieceMachine>()
                        .lambda().eq(MesProducePieceMachine::getPieceId, mesCoveringWork.getPieceId()));
                //先查询中间表是否全部完成
                for (MesProducePieceMachine item : list) {
                    if (item.getMachineType().equals("2")) {    //印刷机
                        if (String.valueOf(producePiece.getPressState()).equals("2")) {
                            num++;
                        }
                    } else if (item.getMachineType().equals("6") || item.getMachineType().equals("5")) {  //封面裁切
                        if (String.valueOf(producePiece.getTrimmingState()).equals("2")) {
                            num++;
                        }
                    } else if (item.getMachineType().equals("4")) { //折页
                        if (String.valueOf(producePiece.getFoldState()).equals("2")) {
                            num++;
                        }
                    } else if (item.getMachineType().equals("7")) {   //覆膜
                        if (String.valueOf(producePiece.getCoveringState()).equals("2")) {
                            num++;
                        }
                    } else if (item.getMachineType().equals("3")) {   //装订
                        if (String.valueOf(producePiece.getBindingState()).equals("2")) {
                            num++;
                        }
                    }
                }
                if (num == list.size()) {
                    // 更改帖数表总的状态
                    producePieceService.update(new UpdateWrapper<ProducePiece>().lambda().set(ProducePiece::getPrintStatus, "2").eq(ProducePiece::getPieceId, mesCoveringWork.getPieceId()));
                }
            }
            //region 更新本次报工所选生产单状态
            //region 本次报工单筛选帖(去重)
            List<String> PieceIdList = mesCovering.getOrderWorkList().stream().map(it -> (it.getPieceId())).collect(Collectors.toList());
            Set pieceSet = new HashSet(PieceIdList);
            PieceIdList.clear();
            PieceIdList.addAll(pieceSet);
            //endregion
            if (PieceIdList.size() > 0) {
                //region 查询这些帖有多少生产单(去重)
                List<ProducePiece> maplist = producePieceService.list(new QueryWrapper<ProducePiece>().lambda().in(ProducePiece::getPieceId, PieceIdList));
                List<String> produceIds = maplist.stream().map(t -> t.getProduceId()).collect(Collectors.toList());
                Set produceIdsSet = new HashSet(produceIds);
                produceIds.clear();
                produceIds.addAll(produceIdsSet);
                //endregion

                //region 更新本次报工生产单状态 - 当前工序进行中
                for (String item : produceIds) {
                    int produceStatus = 13; // 覆膜中
                    Produce produceCurrent = produceService.getById(item);
                    if (produceCurrent != null) {
                        String produceCurrentStatus = produceCurrent.getStatus() == null ? "" : produceCurrent.getStatus();
                        if (!produceCurrentStatus.equals("17") && !produceCurrentStatus.equals("18")) {
                            produceService.update(new UpdateWrapper<Produce>().lambda().set(Produce::getStatus, produceStatus).eq(Produce::getProduceId, item));
                        }
                    }
                }
                //endregion

                //region 遍历查看生产单中是否存在当前工序未完成的帖,如果不存在更新生产单状态 - 当前工序完成
                for (String item : produceIds) {
                    List<Map<String, Object>> countlist = producePieceService.listMaps(new QueryWrapper<ProducePiece>().lambda()
                            .eq(ProducePiece::getProduceId, item)
                            .eq(ProducePiece::getCoveringState, "2")
                            .isNotNull(ProducePiece::getCoveringState));

                    List<Map<String, Object>> countlistsum = producePieceService.listMaps(new QueryWrapper<ProducePiece>().lambda().eq(ProducePiece::getProduceId, item));
                    if (countlist.size() > 0 && countlist.size() == countlistsum.size()) {
                        int produceStatus = 14; // 生产单状态
                        Produce produceCurrent = produceService.getById(item);
                        if (produceCurrent != null) {
                            String produceCurrentStatus = produceCurrent.getStatus() == null ? "" : produceCurrent.getStatus();
                            if (!produceCurrentStatus.equals("17") && !produceCurrentStatus.equals("18")) {
                                produceService.update(new UpdateWrapper<Produce>().lambda().set(Produce::getStatus, produceStatus).eq(Produce::getProduceId, item));
                            }
                        }
                    }
                }
                //endregion
            }
            //endregion

        }

        //region 生成覆膜日报单编号
        Map<String, Object> map = new HashMap<>();
        map.put("columnName", "cover_no");
        map.put("tableName", "mes_covering_order");
        int maxNum = configMapper.getMouthMaxId(map);
        String code = PinYinUtils.getCodeNormal(maxNum, "FMRB");
        //endregion

        //region 保存报工单主子表
        mesCovering.setCoverNo(code);
        mesCoveringService.saveOrUpdate(mesCovering);
        if (mesCovering.getOrderUserList() != null) {
            mesCoveringUserService.remove(new QueryWrapper<MesCoveringUser>().lambda().eq(MesCoveringUser::getOrderId, mesCovering.getPid()));
            mesCoveringUserService.saveBatch(mesCovering.getOrderUserList());
        }
        if (mesCovering.getOrderWorkList() != null) {
            mesCoveringWorkService.remove(new QueryWrapper<MesCoveringWork>().lambda().eq(MesCoveringWork::getOrderId, mesCovering.getPid()));
            mesCoveringWorkService.saveBatch(mesCovering.getOrderWorkList());
        }
        //endregion

        return AjaxResult.success("添加成功", mesCovering.getPid());
    }

    @PostMapping(value = "/updateStatus")
    @Transactional
    public AjaxResult updateStatus(@RequestBody Map<String, String> params) {
        String id = params.get("pid");
        String status = params.get("status");

        // 上报主表机台类型
        String machineType = params.get("machineType");
        MesCovering mesCovering = mesCoveringService.getById(id);
        // 上报主表机台id
        String machineId = mesCovering.getMachineId();
        MesMachine mesMachine = mesMachineService.getById(machineId);
        if (StringUtils.isEmpty(machineType) && mesMachine != null) {
            machineType = mesMachine.getType();
        }

        if (status.equals("1")) { // 车间主任审核通过
            List<MesCoveringWork> coveringWorkList = mesCoveringWorkService.list(new QueryWrapper<MesCoveringWork>().lambda().eq(MesCoveringWork::getOrderId, id));
            List<MesCoveringUser> coveringtUserList = mesCoveringUserService.list(new QueryWrapper<MesCoveringUser>().lambda().eq(MesCoveringUser::getOrderId, id));

//            // 查询有质量事故的完成工作量明细，插入到质量管理模块
//            List<MesCoveringWork> qualityWorklist = coveringWorkList.stream().filter(it -> it.getAccident().equals("1")).collect(Collectors.toList());
//            if (qualityWorklist.size() > 0) {
//                // 插入主表
//                MesQuality mesQuality = new MesQuality();
//                // 生成质量处理单id
//                mesQuality.setId(UUID.randomUUID().toString().replace("-", ""));
//
//                // 生成质量处理单编号
//                Map<String, Object> map = new HashMap<>();
//                map.put("columnName", "code");
//                map.put("tableName", "mes_quality");
//                int maxNum = configMapper.getMouthMaxId(map);
//                String code = PinYinUtils.getCodeNormal(maxNum, "ZLCL");
//
//                mesQuality.setReportId(mesCovering.getPid());
//                mesQuality.setCode(code);
//                mesQuality.setMachineId(machineId);
//                mesQuality.setMachineName(mesCovering.getMachineName());
//                mesQuality.setHeadId(mesCovering.getHeadId());
//                mesQuality.setHeadName(mesCovering.getHeadName());
//                mesQuality.setStatus(1); // 未提交
//                mesQuality.setDisposeType("4");  // 覆膜报工
//                mesQuality.setCreateBy(SecurityUtils.getUsername());
//                mesQuality.setCreateTime(DateUtils.getNowDate());
//                // 插入质量主表
//                mesQualityService.save(mesQuality);
//
//                List<MesQualityUser> mesQualityUserList = new ArrayList<>();
//                for (MesCoveringUser qualitytUser : coveringtUserList) {
//                    MesQualityUser mesQualityUser = new MesQualityUser();
//                    mesQualityUser.setQualityId(mesQuality.getId());
//                    mesQualityUser.setNo(qualitytUser.getUserCode());
//                    mesQualityUser.setName(qualitytUser.getUserName());
//                    mesQualityUser.setWagesPiece(qualitytUser.getPiecePrice());
//                    mesQualityUser.setCreateBy(SecurityUtils.getUsername());
//                    mesQualityUser.setCreateTime(DateUtils.getNowDate());
//                    mesQualityUserList.add(mesQualityUser);
//                }
//                // 批量插入罚款人员
//                mesQualityUserService.saveBatch(mesQualityUserList);
//
//                List<MesQualityWork> mesQualityWorklist = new ArrayList<>();
//                for (MesCoveringWork qualityWork : qualityWorklist) {
//                    MesQualityWork mesQualityWork = new MesQualityWork();
//                    mesQualityWork.setQualityId(mesQuality.getId());
//                    BeanUtils.copyProperties(qualityWork, mesQualityWork);
//                    mesQualityWork.setCreateBy(SecurityUtils.getUsername());
//                    mesQualityWork.setCreateTime(DateUtils.getNowDate());
//                    mesQualityWorklist.add(mesQualityWork);
//                }
//                // 批量插入完成工作量明细
//                mesQualityWorkService.saveBatch(mesQualityWorklist);
//            }

        }
        // 更新报工单状态
        mesCoveringService.update(new UpdateWrapper<MesCovering>().lambda().set(MesCovering::getStatus, status).eq(MesCovering::getPid, id));
        return AjaxResult.success("更新成功");
    }

    @PostMapping(value = "/getById")
    public AjaxResult getById(@RequestBody Map<String, String> params) {
        String id = params.get("pid");
        MesCovering mesCovering = mesCoveringService.getById(id);
        String machineId = mesCovering.getMachineId();
        String machineType = "";
        MesMachine mesMachine = mesMachineService.getById(machineId);
        if (mesMachine != null) {
            machineType = mesMachine.getType();
        }
        List<MesCoveringUser> mesCoveringUserList = mesCoveringUserService.list(new QueryWrapper<MesCoveringUser>().lambda().eq(MesCoveringUser::getOrderId, mesCovering.getPid()));
        List<MesCoveringWork> mesCoveringWorkList = mesCoveringWorkService.list(new QueryWrapper<MesCoveringWork>().lambda()
                .eq(MesCoveringWork::getOrderId, mesCovering.getPid()).orderByAsc(MesCoveringWork::getBreedType));
        mesCovering.setOrderUserList(mesCoveringUserList);
        mesCovering.setOrderWorkList(mesCoveringWorkList);

//        // 循环查询累计上报数量 和 最大允许上报量
//        MesReportWork.selectMesReportTotalNum(mesCovering, machineId, machineType);  // 覆膜报工

//        for (MesCoveringWork coveringWork : mesCoveringWorkList) {
//            // 生产单报工查询累计上报数量
//            MesProducePieceMachine producePieceMachine = producePieceMachineService.getOne(new QueryWrapper<MesProducePieceMachine>().lambda()
//                    .eq(MesProducePieceMachine::getPieceId, coveringWork.getPieceId())
//                    .eq(MesProducePieceMachine::getMachineId, machineId)
//                    .last("LIMIT 1")
//            );
//            if (producePieceMachine != null) {
//                coveringWork.setTotalNum(producePieceMachine.getTotal());
//            }
//        }

        return AjaxResult.success("查询成功", mesCovering);
    }

    @PostMapping(value = "/deleteById")
    public AjaxResult deleteById(@RequestBody Map<String, String> params) {
        String id = params.get("pid");
        mesCoveringService.removeById(id);
        mesCoveringUserService.remove(new QueryWrapper<MesCoveringUser>().lambda().eq(MesCoveringUser::getOrderId, id));
        mesCoveringWorkService.remove(new QueryWrapper<MesCoveringWork>().lambda().eq(MesCoveringWork::getOrderId, id));
        return AjaxResult.success("删除成功");
    }
}
